//
//  JKMacro.m
//  JKFoundation
//
//  Created by JK on 07/08/2017.
//  Copyright © 2017 Shanghai DataSeed Information Technology Co.,Ltd. All rights reserved.
//

#import "JKMacro.h"

NSString* const JKEmptyString = @"";
NSString* const JKEmptyUUIDString = @"00000000-0000-0000-0000-000000000000";

UIColor* JKColorHex(NSString* color)
{
    static NSString* const CLEAR_COLOR = @"CLEAR";
    if ([color isEqualToString:CLEAR_COLOR]) {
        return [UIColor clearColor];
    }
    
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

CGRect JKRectSetOriginX(CGRect rect, CGFloat originX) {
    CGPoint origin = rect.origin;
    origin.x = originX;
    rect.origin = origin;
    return rect;
}

void JKDispatchSyncOnMainQueue(void (^block)(void))
{
    if ([NSThread isMainThread])
    {
        block();
    }
    else
    {
        dispatch_sync(dispatch_get_main_queue(), block);
    }
}

UIEdgeInsets JKSafeAreaInsets(void){
    UIEdgeInsets safeAreaInsets = UIEdgeInsetsZero;
    if (@available(iOS 11.0, *)) {
        safeAreaInsets = [[UIApplication sharedApplication] delegate].window.safeAreaInsets;
    }
    return safeAreaInsets;
}

BOOL JKHasNeatBang(void){
    UIEdgeInsets safeAreaInsets = JKSafeAreaInsets();
    BOOL hasNeatBang = (safeAreaInsets.top>20.0||safeAreaInsets.left>20.0||safeAreaInsets.right>20.0||safeAreaInsets.bottom>20.0);
    return  hasNeatBang;
}

